﻿using System;
using System.Collections.Generic;
using NGinnBPM.MessageBus;
using NGinnBPM.Runtime.Events;
using NGinnBPM.Lib.Data;
using NGinnBPM.Lib.Schema;
using NGinnBPM.Lib.Exceptions;
using System.Text;
using NGinnBPM.Services;
using System.Data;
using System.Data.SqlTypes;
using System.Runtime.Serialization;

namespace NGinnBPM.Runtime.Tasks
{
    [Serializable]
    [DataContract]
    public class SQLTaskInstance : AtomicTaskInstance
    {
        public SQLTaskInstance()
        {
            DriverType = "oledb";
        }

        [DataMember]
        [TaskParameter(IsInput = true, Required = true)]
        public string ConnectionString { get; set; }

        [DataMember]
        [TaskParameter(IsInput = true, Required = false)]
        public string DriverType { get; set; }

        [DataMember]
        [TaskParameter(IsInput = true, Required = true)]
        public string Query { get; set; }

        private IDbConnection GetConnection()
        {
            IDbConnection conn;
            if (DriverType == "sql")
            {
                conn = new System.Data.SqlClient.SqlConnection();
            }
            else if (DriverType == "oledb")
            {
                conn = new System.Data.OleDb.OleDbConnection();
            }
            else if (DriverType == "odbc")
            {
                conn = new System.Data.Odbc.OdbcConnection();
            }
            else
            {
                Type tp = Type.GetType(DriverType);
                if (tp == null) throw new TaskRuntimeException("Invalid driver type: " + DriverType).SetInstanceId(InstanceId);
                conn = (IDbConnection) Activator.CreateInstance(tp);
            }
            conn.ConnectionString = ConnectionString;
            conn.Open();
            return conn;
        }

        public override void Enable(Dictionary<string, object> inputData)
        {
            base.Enable(inputData);
            ExecuteQuery();
            Complete(null, null);
        }

        protected void ExecuteQuery()
        {
            try
            {
                using (IDbConnection conn = GetConnection())
                {
                    using (IDbCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = Query;
                        IDbDataParameter param = cmd.CreateParameter();
                        throw new NotImplementedException();
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error("Error executing query {0}: {1}", Query, ex);
                throw;
            }
        }
    }
}
